package com.hjl.web.servlet;

import com.hjl.domain.Emp_Dept_Job_inf;
import com.hjl.domain.Employee_inf;
import com.hjl.domain.PageBean;
import com.hjl.service.EmployeeService;
import com.hjl.service.impl.EmployeeServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工表现层
 *
 * @author Lenovo
 * @version 1.0
 * @date 2021/10/8 11:26
 */
@WebServlet("/employees/*")
public class EmployeeServlet extends BaseServlet {
    private EmployeeService employeeService = new EmployeeServiceImpl();
    String prefix = "/WEB-INF/jsp/employee/";
    String suffix = ".jsp";

    /**
     * 跳转WEB-INF里的jsp
     */
    public void toList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(prefix + "employeelist" + suffix).forward(req, resp);
    }

    public void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(prefix + "employeeadd" + suffix).forward(req, resp);
    }

    public void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(prefix + "employeeedit" + suffix).forward(req, resp);
    }

    /**
     * 储存所有职位和部门的map
     */
    Map<Integer, String> jobMap = new HashMap<>();
    Map<Integer, String> deptMap = new HashMap<>();

    /**
     * 分页
     */
    public void findEmployeeByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取数据（当前页码和行数）
        String currentPage = req.getParameter("currentPage");
        String rows = req.getParameter("rows");
        //默认第1页，5行
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "5";
        }
        Map<String, String[]> condition = req.getParameterMap();
        PageBean<Emp_Dept_Job_inf> pb = employeeService.findEmployeeByPage(currentPage, rows, condition);
        List<Emp_Dept_Job_inf> employees = employeeService.findAllEmployee();
        for (Emp_Dept_Job_inf e : employees) {
            jobMap.put(e.getJob_id(), e.getJob_name());
            deptMap.put(e.getDept_id(), e.getDept_name());
        }

        req.setAttribute("employees", pb);
        req.setAttribute("condition", condition);
        //下面还要用，设成session
        req.getSession().setAttribute("jobMap", jobMap);
        req.getSession().setAttribute("deptMap", deptMap);

        req.getRequestDispatcher("/employees/toList").forward(req, resp);
    }

    /**
     * 删除选中
     *
     * @author Lenovo
     * @date 2021/10/8 21:58
     */
    public void delSelected(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] ids = req.getParameterValues("id");
        employeeService.delSelect(ids);
        resp.sendRedirect(req.getContextPath() + "/employees/findEmployeeByPage");
    }

    /**
     * 查询单个（用于编辑）
     *
     * @author Lenovo
     * @date 2021/10/8 21:58
     */
    public void findEmployee(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String id = req.getParameter("id");
        //调用service方法
        Emp_Dept_Job_inf employee = employeeService.findEmployeeById(id);


        //存入request
        req.setAttribute("employee", employee);
        System.out.println(employee);
        //转发到employeeedit.jsp
        req.getRequestDispatcher("/employees/toEdit").forward(req, resp);
    }

    /**
     * 更新
     *
     * @author Lenovo
     * @date 2021/10/8 21:58
     */
    public void updateEmployee(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编码
        req.setCharacterEncoding("utf-8");
        //获取map
        Map<String, String[]> map = req.getParameterMap();
        Employee_inf employee = new Employee_inf();
        try {
            //封装
            BeanUtils.populate(employee, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
//        调用service方法
        employeeService.updateEmployee(employee);
        //重定向回去
        resp.sendRedirect(req.getContextPath() + "/employees/findEmployeeByPage");
    }

    /**
     * 封装好数据
     *
     * @author Lenovo
     * @date 2021/10/8 22:14
     */
    public void loadMap(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        List<Emp_Dept_Job_inf> employees = employeeService.findAllEmployee();
        for (Emp_Dept_Job_inf e : employees) {
            jobMap.put(e.getJob_id(), e.getJob_name());
            deptMap.put(e.getDept_id(), e.getDept_name());
        }
        req.getSession().setAttribute("jobMap", jobMap);
        req.getSession().setAttribute("deptMap", deptMap);

        req.getRequestDispatcher("/employees/toAdd").forward(req, resp);
    }

    /**
     * 添加
     *
     * @author Lenovo
     * @date 2021/10/8 21:58
     */
    public void addEmployee(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");

        //获得参数
        Map<String, String[]> map = req.getParameterMap();
        //封装对象
        Employee_inf employee = new Employee_inf();
        try {
            BeanUtils.populate(employee, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        employeeService.addEmployee(employee);
        resp.sendRedirect(req.getContextPath() + "/employees/loadMap");
        //转发到employeeadd.jsp
//        req.getRequestDispatcher("/employee/employeeadd.jsp").forward(req,resp);
    }

    /**
     * 获取身份证号
     *
     * @author Lenovo
     * @date 2021/10/8 21:59
     */
    public void getCardId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String card_id = req.getParameter("cardId");
        String id = req.getParameter("Id");
        List<String> cardIds = null;
        //ajax判断
        if (id == null) {
            //添加时
            cardIds = employeeService.findCardIds();
        } else {
            //更新时（排除原来的）
            cardIds = employeeService.findCardIds(id);
        }
        //遍历返回的list，设置相应flag，并设置map
        Map<String, Object> map = new HashMap<>(16);
        boolean flag = false;
        for (String cardId : cardIds) {
            if (cardId.equals(card_id)) {
                flag = true;
                break;
            }
        }
        if (flag) {
            map.put("msg", "用户名已存在");
            map.put("exist", true);
        } else {
            map.put("msg", "用户名可用");
            map.put("exist", false);
        }
        writeValue(map, resp);
    }
}
